﻿using UnityEngine;
using System.Collections;
using TileMapClasses;
using AIClasses;
using KeyBindings;

namespace GeneralStorageClasses
{
	/// <summary>
	/// Game manager. Holds all the data that needs to be kept throughout the gameplay.
	/// </summary>
	public class GameManager : MonoBehaviour
	{
		private static GameManager m_instance;
		private WorldGeneration worldGen;
		private StoryManager storyManager;
		private Vector2 worldSize;
		private KeyManager Keybindings;
		private AIManager AiMan;
		public tileManager tileman;
		public GameObject prefab;
		public int battleWin;

		void Start ()
		{
			m_instance = this;

			//Make this stay around all the time
			DontDestroyOnLoad (transform.gameObject);

			//Load in stories from XML file
			storyManager = new StoryManager ("stories.xml");

			Keybindings = KeyManager.Instance;

			//Wait until tileManager is loaded
			tileManager.TileManagerFinishedLoading += PopulateLevel;
		
			//Create a world Gernerator with a seed
			worldGen = new WorldGeneration (0.55f);

			//Always have a min of 5 x 5 map
			worldSize = new Vector2 (5, 5);

			AiMan = new AIManager ();

			battleWin = 0;

			if (HoldingClass.Instance.prefab != null) {
				if (tileman == null) {
					GameObject hold = (GameObject)Instantiate (HoldingClass.Instance.prefab);
					tileman = (tileManager)hold.GetComponent ("tileManager");
				}
			}
		}

		/// <summary>
		/// Sets the game settings for generation.
		/// </summary>
		/// <param name="seed">Seed.</param>
		/// <param name="width">Width.</param>
		/// <param name="height">Height.</param>
		public void SetGameSettings (float seed, float width, float height)
		{
			//Set these settings (should be set from new game menu
			worldGen.Seed = seed;
			worldSize.x = width;
			worldSize.y = height;
		}

		/// <summary>
		/// Populates the level.
		/// </summary>
		public void PopulateLevel ()
		{
			//Init the tiles after it has called this function
			tileManager.Instance.initTileManager (worldSize.x, worldSize.y);
		
			//Generate world 
			worldGen.GenTiles ();

//			//After use, don't listen for the event
//			tileManager.TileManagerFinishedLoading -= PopulateLevel;
		}

		/// <summary>
		/// Gets the instance.
		/// </summary>
		/// <value>The instance.</value>
		public static GameManager Instance {
			get {
				if (m_instance == null) {
					//This will create a GameManager if none is found, this happens when u have not visited the mainmenu
					GameObject managerObject = new GameObject ("GameMan");
					managerObject.AddComponent ("GameManager");

					//Throw error if null but create it anyway we always need a GM
					Debug.LogError ("GameManager: Instance is null, Creating new manager(Ignore this if running from a screen other than MainMenu");
				}
				return m_instance;
			}
		}
	}
}
